home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C20 / MultiSet1.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.7 KB  |  68 lines

  1. //: C20:MultiSet1.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Demonstration of multiset behavior
  7. #include <iostream>
  8. #include <set>
  9. #include <algorithm>
  10. #include <ctime>
  11. using namespace std;
  12.  
  13. class X {
  14.   char c; // Used in comparison
  15.   int i; // Not used in comparison
  16.   // Don't need default constructor and operator=
  17.   X();
  18.   X& operator=(const X&);
  19.   // Usually need a copy-constructor (but the
  20.   // synthesized version works here)
  21. public:
  22.   X(char cc, int ii) : c(cc), i(ii) {}
  23.   // Notice no operator== is required
  24.   friend bool operator<(const X& x, const X& y) {
  25.     return x.c < y.c;
  26.   }
  27.   friend ostream& operator<<(ostream& os, X x) {
  28.     return os << x.c << ":" << x.i;
  29.   }
  30. };
  31.  
  32. class Xgen {
  33.   static int i;
  34.   // Number of characters to select from:
  35.   static const int span = 6;
  36. public:
  37.   Xgen() { srand(time(0)); }
  38.   X operator()() {
  39.     char c = 'A' + rand() % span;    
  40.     return X(c, i++);
  41.   }
  42. };
  43.  
  44. int Xgen::i = 0;
  45.  
  46. typedef multiset<X> Xmset;
  47. typedef Xmset::const_iterator Xmit;
  48.  
  49. int main() {
  50.   Xmset mset;
  51.   // Fill it with X's:
  52.   generate_n(inserter(mset, mset.begin()), 
  53.     25, Xgen());
  54.   // Initialize a regular set from mset:
  55.   set<X> unique(mset.begin(), mset.end());
  56.   copy(unique.begin(), unique.end(), 
  57.     ostream_iterator<X>(cout, " "));
  58.   cout << "\n----\n";
  59.   // Iterate over the unique values:
  60.   for(set<X>::iterator i = unique.begin();
  61.       i != unique.end(); i++) {
  62.     pair<Xmit, Xmit> p = mset.equal_range(*i);
  63.     copy(p.first, p.second, 
  64.       ostream_iterator<X>(cout, " "));
  65.     cout << endl;
  66.   }
  67. } ///:~
  68.